<template>
  <div class="code-box">
    <!-- <div id="code"></div> -->
    <webview :src="url" style="width: 400px; height: 300px" @did-navigate="handleDidNav"></webview>
  </div>
</template>
<script setup lang="ts">
import { onMounted, ref } from "vue";
import { getLoginParam } from '@api/login'
import useLogin from '@hooks/useLogin'

let scDom: HTMLScriptElement | null = null

// onMounted(() => {
//   if (!scDom) {
//     scDom = document.createElement('script')
//     scDom.src = "http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"
//     document.body.appendChild(scDom)
//     scDom.onload = async () => {
//       let res = await getLoginParam()
//       let { redirectUri, appid, scope, state} = res.data
//       new WxLogin({
//         // self_redirect:true, // 打开网页形式，还是直接展示二维码
//         id: "code", 
//         appid,  // 名字一样可以简化
//         scope, 
//         redirect_uri: encodeURIComponent(redirectUri),
//         state,
//         href: "data:text/css;base64,LmltcG93ZXJCb3ggLnFyY29kZSB7d2lkdGg6IDIwMHB4O30NCi5pbXBvd2VyQm94IC50aXRsZSB7ZGlzcGxheTogbm9uZTt9DQouaW1wb3dlckJveCAuaW5mbyB7ZGlzcGxheTogbm9uZX0NCi5zdGF0dXNfaWNvbiB7ZGlzcGxheTogbm9uZX0NCi5pbXBvd2VyQm94IC5zdGF0dXMge3RleHQtYWxpZ246IGNlbnRlcjt9DQouaW1wb3dlckJveCAucXJjb2RlIHt3aWR0aDogMjMwcHg7bWFyZ2luLXRvcDogO2JvcmRlcjogbm9uZTt9DQo=" // 给code添加一些样式，是base64编码
//       });
//     }
//   }
// })
let url = ref('')
onMounted(async () => {
  let res = await getLoginParam()
  let { redirectUri, appid, scope, state} = res.data
  // url.data = `https://open.weixin.qq.com/connect/qrconnect?appid=${appid}&redirect_uri=${encodeURIComponent(redirectUri)}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`
  url.value = `https://open.weixin.qq.com/connect/qrconnect?appid=${appid}&redirect_uri=${decodeURIComponent(redirectUri)}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`
  console.log(url.value)
})
// 监听url的变化
const handleDidNav = (event)=> {
  console.log(event.url)
  if(event.url){
    const url = new URL(event.url)
    const urlParams = new URLSearchParams(url.search)
    const token = urlParams.get('token')
    console.log(token)
    useLogin(token)
  }
}
</script>